package cn.cutie.clot.gateway.other;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @Description:
 * @Author: Cutie
 * @CreateDate: 2024/5/21 20:42
 * @Version: 0.0.1
 */
@Component
public class HelloHandler {
    Mono<ServerResponse> handle(ServerRequest request){
        // 模拟调用rpc
        String url = "http://127.0.0.1:8081/clotrpc";
        String requestJson = """
                {
                  "service": "cn.cutie.clotrpc.demo.api.OrderService",
                  "methodSign": "findById@1_java.lang.Integer",
                  "args": [200]
                }
                """;
        // 可以反射获取httpclient，有哪个就用哪个
        WebClient client = WebClient.create(url);
        Mono<ResponseEntity<String>> entity = client.post()
                .header("Content-Type", "application/json")
                .bodyValue(requestJson)
                .retrieve()
                .toEntity(String.class);
        Mono<String> body = entity.map(ResponseEntity::getBody);
        body.subscribe(souce -> System.out.println(souce));
        return ServerResponse.ok()
                .header("Content-Type", "application/json")
                .header("clot.gw.version", "v1.0.0")
                .body(body, String.class);

        // entity.map还是一个Mono，要用body不能用bodyValue
//        return ServerResponse.ok().body(entity.map(ResponseEntity::getBody), String.class);


//        return ServerResponse.ok().body(entity, String.class);
//                .bodyToMono(String.class)
//                .flatMap(response -> ServerResponse.ok().bodyValue(response));
//        return ServerResponse.ok().bodyValue("Hello, Spring WebFlux");
    }

}
